package com.mdisoft.quotogram.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class API {

	private Context _context;
	private UserSettings _s;
	
	private DefaultHttpClient _httpClient;
	
	public API(Context context) {
		_context = context;
		_s = new UserSettings(_context);
	}
	
	
	public boolean AddQuote(String quote, String saidby, String username, String tags, String source, String timestamp) {		
		_httpClient = new DefaultHttpClient();
		//_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, _creds);
		HttpPost post = new HttpPost("http://api.quotogram.com/quotes/add");
		String json = String.format("{\"quote\":\"%s\",\"saidby\":\"%s\",\"lat\":\"%s\",\"lon\":\"%s\",\"username\":\"%s\",\"tags\":\"%s\",\"source\":\"%s\",\"timestamp\":\"%s\"}", 
				quote, saidby, String.valueOf(_s.getLatitude()), String.valueOf(_s.getLongitude()), username, tags, source, timestamp);
		try {
			post.setEntity(new StringEntity(json, HTTP.UTF_8));
			post.setHeader("Content-type", "application/json");
			post.setHeader("Content-lenght", String.valueOf(json));
			HttpResponse response = _httpClient.execute(post);
			InputStream stream = response.getEntity().getContent();			
			if (response.getStatusLine().getStatusCode() == 200) {
				JSONObject object = new JSONObject(convertStreamToString(stream));				
				return Boolean.parseBoolean(object.getString("result").toLowerCase());
			}
			else 
				return false;
		} catch (ClientProtocolException e) { e.printStackTrace(); return false; }
		  catch (IOException e) { e.printStackTrace(); return false; } 
		  catch (JSONException e) {	e.printStackTrace(); return false; }		  
	}
	
	
	/**
	 * Check if data connection is available
	 * @param Context
	 * @return true / false
	 */
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni!=null && ni.isAvailable() && ni.isConnected())
	        return true;
	    return false;
	}
	
	
	/**
	 * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
	 * @param InputStream
	 * @return String
	 */
	private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); }} 
        catch (IOException e) { e.printStackTrace(); } 
        finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); }}
        return sb.toString();
	}
}
